package com.sz.framework.utils;

import android.app.Activity;

import java.util.NoSuchElementException;
import java.util.Stack;

public class ActivityStackManager {
    /**
     * 自定义Activity栈（用于自定义管理）
     */
    private static Stack<Activity> activityStack;
    private static ActivityStackManager instance = new ActivityStackManager();

    private ActivityStackManager() {
    }

    public static ActivityStackManager getInstance() {
        return instance;
    }

    /**
     * 把某个Activity从栈中移除（没有finish）
     *
     * @param activity
     */
    public void popActivity(Activity activity) {
        if (activity != null) {
            activityStack.remove(activity);
        }

    }

    /**
     * 把当前Activity从栈中移除（没有finish）
     */
    public void popActivity() {
        Activity activity = currentActivity();
        if (activity != null) {
            activityStack.remove(activity);
            activity = null;
        }
    }


    /**
     * 销毁当前Activity
     */
    public void popActivityWithFinish() {
        Activity activity = currentActivity();
        if (activity != null) {
            activity.finish();
            activity = null;
        }
    }

    /**
     * 销毁指定activity（在每个Activity的onBackPressed方法中调用）
     *
     * @param activity
     */
    public void popActivityWithFinish(Activity activity) {
        if (activity != null) {
            activity.finish();
            activityStack.remove(activity);

        }

    }

    /**
     * 获得当前Activity
     *
     * @return
     */
    public Activity currentActivity() {
        Activity activity = null;
        try {
            activity = activityStack.lastElement();
        } catch (NoSuchElementException ex) {
            ex.printStackTrace();
        }
        return activity;
    }

    /**
     * 添加Activity（必须在每个Activity的onCreate方法中调用）
     *
     * @param activity
     */
    public void pushActivity(Activity activity) {
        if (activityStack == null) {
            activityStack = new Stack<Activity>();
        }
        activityStack.add(activity);

    }

    /**
     * 销毁除了某一个的所有Activity
     *
     * @param cls 不销毁的Activity名字，如果为null，则销毁所有Activity
     */
    public void popAllActivityExceptOne(Class cls) {

        for (int i = 0; i < activityStack.size(); i++) {
            Activity act = activityStack.get(i);
            if (act.getClass().equals(cls)) {
                continue;
            }
            popActivityWithFinish(act);
        }


    }

    public void popAllActivity() {
        for (int i = 0; i < activityStack.size(); i++) {
            Activity act = activityStack.get(i);
            if (null != act) {
                act.finish();
            }
        }
        activityStack.clear();
    }


}
